package cn.edu.zut.hhr.service.impl;

import cn.edu.zut.hhr.service.UpLoadService;
import cn.edu.zut.hhr.vo.RestResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class UpLoadServiceImpl implements UpLoadService {

    @Value("${img.direct}")
    private String direct;
    @Value("${img.DN}")
    private String domainName;

    @Override
    public RestResponse upLoad(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String realName = UUID.nameUUIDFromBytes(multipartFile.getBytes())+originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
        String filePath = null;
        File file = new File(direct+File.separator+realName);
        if(domainName != null && !domainName.equals("")){
            filePath = domainName+File.separator+direct+ File.separator+realName;
        } else{
            filePath = direct+ File.separator+realName;
        }
        if(!file.exists()){
            file.createNewFile();
        } else{
            return RestResponse.success(filePath);
        }
        multipartFile.transferTo(file);
        return RestResponse.success(filePath);
    }
}
